package com.application.lucky.manager;


import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.application.lucky.Lucky;
import com.application.lucky.bean.UserBean;
import com.application.lucky.bean.jsonBean.BankItemBean;
import com.application.lucky.bean.sqliteBean.BankBean;
import com.application.lucky.fragment.main.LoginEvent;
import com.application.lucky.gen.UserBeanDao;
import com.application.lucky.request.CallBackEx;
import com.application.lucky.request.IMTokenResuest;
import com.application.lucky.request.LoginRequest;
import com.application.lucky.request.RedPRequest;
import com.application.lucky.request.UserRequest;
import com.application.lucky.utils.ConnUtil;
import com.application.lucky.utils.Flog;
import com.application.mylibrary.utils.EventBusUtils;
import com.application.mylibrary.utils.LogUtils;
import com.application.mylibrary.utils.SharedPreferencesUtil;
import com.application.mylibrary.utils.ToastUtils;
import com.baselib.libnetwork.net.libnetworkcomponent.BaseResponse;
import com.baselib.libnetwork.net.libnetworkcomponent.RequestCommonParams;
import com.qunar.im.ui.sdk.QIMSdk;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.schedulers.Schedulers;


public class UserManagers {
    public static final String Token = "token";
    public static final String LOGIN_NAME = "login_name";
    private final UserBeanDao userBeanDao;
    private UserBean userBean;
    private String payPassword;

    private UserManagers() {
        userBeanDao = Lucky.getApplication().getDaoSession().getUserBeanDao();
        List<UserBean> list = userBeanDao.getSession().queryBuilder(UserBean.class).list();
        if (list.size() > 0) {
            userBean = list.get(0);
        }

    }


    public void setUserBean(UserBean userBean) {
        this.userBean = userBean;
    }

    public void saveToken(String token) {
        SharedPreferencesUtil.saveString(Lucky.getApplication(), Token, token);
    }

    public String getToken() {
        return SharedPreferencesUtil.getString(Lucky.getApplication(), Token, "");
    }

    public void setPayPassword(String payPassword) {
//        IMPreferencesUtil.saveString(Lucky.getApplication(),"payPassword",payPassword);
        this.payPassword = payPassword;
    }

    public static UserManagers getInstance() {
        return InnerClass.userManager;
    }

    public void saveLoginName(String username) {
        SharedPreferencesUtil.saveString(Lucky.getApplication(), LOGIN_NAME, username);
    }

    public String getLoginName() {
        return SharedPreferencesUtil.getString(Lucky.getApplication(), "login_name", "lucky");
    }

    private String invite;

    public void invite(String s1) {
        invite = s1;
    }

    private static class InnerClass {
        private static UserManagers userManager = new UserManagers();
    }

    //没有token的时候  就是没有登录  需要重新登录
    public boolean isLogin() {
        String token = getToken();
        LogUtils.i("token===" + token);
        RequestCommonParams.getInstance().updateToken(token);
        return !TextUtils.isEmpty(token);

    }

    public UserBean getUserBean() {
        return userBean;
    }

    public String getUserId() {
        if (userBean != null) {
            return userBean.getUserId() + "";
        }
        return "";
    }

    public String getUserName() {
        if (userBean != null) {
            return userBean.getNickName();
        }
        return "";
    }

    public String getShowName() {
        if (userBean != null) {
            return userBean.getShowName();
        }
        return "";
    }

    public String getPic() {
        if (userBean != null) {
            return userBean.getHeadPic();
        }
        return "";
    }

    private double balance = 0;

    public double getBalance() {
        return balance / 100.0;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    //加载自己的用户信息
    public void loadUserBean() {
        new UserRequest().getSelfData(new CallBackEx<BaseResponse<UserBean>>() {


            @Override
            public void onSuccess(BaseResponse<UserBean> stringBaseResponse) {
                Flog.d("UserManagers", "onSuccess-getSelfData:" + stringBaseResponse.dataInfo);
                UserBean dataInfo = stringBaseResponse.dataInfo;
                if (userBeanDao != null && dataInfo != null) {
                    userBean = dataInfo;
                    userBeanDao.insertOrReplace(dataInfo);
                }
                loadBalance();
                loadPayPw();
                UserManagers.getInstance().loginIm();
                EventBusUtils.post(stringBaseResponse.dataInfo);
                loadSelfBankInfo();
            }

            @Override
            protected void OnFailureNeedData(int code, BaseResponse<UserBean> error) {
                if (code == 20002) {
                    new UserRequest().user_init_attr(invite, new CallBackEx<BaseResponse<UserBean>>() {
                        @Override
                        public void onFailed(int code) {
                            ToastUtils.show("请求失败" + code);
                        }

                        @Override
                        public void onSuccess(BaseResponse<UserBean> stringBaseResponse) {
                            UserBean dataInfo = stringBaseResponse.dataInfo;
                            if (userBeanDao != null && dataInfo != null) {
                                userBean = dataInfo;
                                userBeanDao.insertOrReplace(dataInfo);
                            }
                            UserManagers.getInstance().loginIm();
                            EventBusUtils.post(stringBaseResponse.dataInfo);
                            if (!TextUtils.isEmpty(invite)) {
                                new LoginRequest().invite(invite, null);
                            }
                        }
                    });
                }
            }

            @Override
            public void onFailed(int code) {

            }
        });
    }

    public void loadPayPw() {

        new RedPRequest().red_password(new CallBackEx<BaseResponse<String>>() {
            @Override
            public void onFailed(int code) {

            }

            @Override
            public void onSuccess(BaseResponse<String> stringBaseResponse) {
                String dataInfo = stringBaseResponse.dataInfo;
                setPayPassword(dataInfo);
            }
        });
    }

    public String getPayPassword() {

        return payPassword;
    }

    public boolean isSetPayPW() {
//        Log.i("hahahah", "password===" + payPassword);
        return !TextUtils.isEmpty(getPayPassword());
    }

    public void loadBalance() {
        new RedPRequest().red_balance(new CallBackEx<BaseResponse<Integer>>() {
            @Override
            public void onFailed(int code) {

            }

            @Override
            public void onSuccess(BaseResponse<Integer> integerBaseResponse) {
                balance = integerBaseResponse.dataInfo;
            }
        });
    }

    //登录聊天
    public void loginIm() {
        String imLoginName = getIMLoginName();
        String imPassword = getIMPassword();
        if (TextUtils.isEmpty(imLoginName)) {
            getImToken();

        } else {
            QIMSdk.getInstance().login(imLoginName, imPassword, new QIMSdk.LoginStatesListener() {
                @Override
                public void isScuess(boolean isScuess, String message) {
                    LogUtils.i("imtoken===" + message);
                    if (!isScuess) {

                        ToastUtils.show("网络异常！");
                        getImToken();
                    }
                    EventBusUtils.post(new LoginEvent());

                }
            });
        }


    }

    private int count = 0;

    private void getImToken() {

        new IMTokenResuest().getIMToken(new CallBackEx<BaseResponse<String>>() {
            @Override
            public void onSuccess(BaseResponse<String> imTokenBeanBaseResponse) {
                count = 0;
                String dataInfo = imTokenBeanBaseResponse.dataInfo;
                if (!TextUtils.isEmpty(dataInfo)) {
                    JSONObject object = JSON.parseObject(dataInfo);
                    String user_id = object.getString("user_id");
                    String pwd_salt = object.getString("pwd_salt");
                    LogUtils.i("imtoken===userid==" + user_id + "=====pwd_salt====" + pwd_salt);
                    setIMLoginName(user_id);
                    setIMPassword(pwd_salt);
                    loginIm();
                }
            }

            @Override
            public void onFailed(int code) {
                count++;
//                if (code==20001){
                if (count <= 5) {
                    getImToken();
                }

//                }
            }


        });
    }

    //用户退出登录
    public void loginOut() {
        try {
            if (userBean != null) {
                userBeanDao.delete(userBean);
            }

            String login_name = getLoginName();
//        new LoginRequest().loginOut(login_name, null);
            saveLoginName("");
            setIMLoginName("");
            saveToken("");
            setIMPassword("");
            payPassword = "";
            balance = 0;
            userBean = new UserBean();
            QIMSdk.getInstance().signOut();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public String getIMLoginName() {
        return SharedPreferencesUtil.getString(Lucky.getApplication(), "imloginname", "");
    }

    public void setIMLoginName(String name) {
        SharedPreferencesUtil.saveString(Lucky.getApplication(), "imloginname", name);
    }

    public String getIMPassword() {
        return SharedPreferencesUtil.getString(Lucky.getApplication(), "impassword", "");
    }

    public void setIMPassword(String password) {
        SharedPreferencesUtil.saveString(Lucky.getApplication(), "impassword", password);
    }

    public boolean isTourist() {
        return userBean == null || TextUtils.isEmpty(userBean.getRealName())
                || TextUtils.isEmpty(userBean.getBankAddress())
                || TextUtils.isEmpty(userBean.getBankName())
                || TextUtils.isEmpty(userBean.getBank())
                || TextUtils.isEmpty(userBean.getMobile());
    }


    private void loadSelfBankInfo() {
        Observable.create(new ObservableOnSubscribe<List<BankBean>>() {

            @Override
            public void subscribe(final ObservableEmitter<List<BankBean>> emitter) throws Exception {
                new UserRequest().getAlreadyBindBank(new CallBackEx<BaseResponse<List<BankItemBean>>>() {
                    @Override
                    public void onFailed(int code) {

                    }

                    @Override
                    public void onSuccess(BaseResponse<List<BankItemBean>> listBaseResponse) {
                        if (ConnUtil.isEmpty(listBaseResponse.dataInfo)) {
                            return;
                        }

                        List<BankItemBean> resBeanList = listBaseResponse.dataInfo;
                        BankItemBean firstBean = resBeanList.get(0);
                        if (userBean != null) {
                            userBean.setName(firstBean.name);
//                            userBean.setRealName(firstBean.name);
                            userBean.setBankAddress(firstBean.bankAddress);
                            userBean.setBank(firstBean.bank);
                            userBean.setBankName(firstBean.bankName);
                            userBeanDao.insertOrReplace(userBean);
                        }
                    }
                });
            }
        }).subscribeOn(Schedulers.single()).subscribe();
    }
}
